﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO.IsolatedStorage;
using System.Windows.Navigation;

using Angerona.Model;
using System.Windows.Media.Imaging;

namespace Angerona
{
    public partial class Vehicles : PhoneApplicationPage
    {
        IsolatedStorageSettings VehiclesData = IsolatedStorageSettings.ApplicationSettings;
        public Vehicles()
        {
            InitializeComponent();
            EditContentPanel();
            ApplicationBarInitializer();
        }

        private void ApplicationBarInitializer()
        {
            // Set the page's ApplicationBar to a new instance of ApplicationBar.
            ApplicationBar = new ApplicationBar();

            ApplicationBar.Mode = ApplicationBarMode.Default;
            ApplicationBar.Opacity = 1.0;
            ApplicationBar.IsVisible = true;
            ApplicationBar.IsMenuEnabled = false;
            // add button
            ApplicationBarIconButton btn_add = new ApplicationBarIconButton();
            btn_add.IconUri = new Uri("/Img/appbar_add.png", UriKind.Relative);
            btn_add.Text = AngeronaLang.add;
            ApplicationBar.Buttons.Add(btn_add);
            btn_add.Click += new EventHandler(btn_add_Click);
        }

        /// <summary>
        /// handeler for the add on applicationBar
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_add_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/AddCar.xaml", UriKind.Relative));
        }

        private void EditContentPanel()
        {
            UIElementCollection elements = ContentPanel.Children;
            while (elements.Count > 0)
            {
                UIElement temp = elements[0];
                if (temp.GetType() == typeof(Button))
                    ContentPanel.Children.Remove(temp);
            }
            while (ContentPanel.RowDefinitions.Count > 0)
                ContentPanel.RowDefinitions.RemoveAt(0);
            int k = 0;
            List<int> IDlist = App.ViewModel.getVehicleIdlist();
            
            int ncar = App.ViewModel.getNumbersOfVehicles(); //will be used for numer of car (from db)
            if (ncar % 2 == 1)
                for (int i = 1; i <= ((ncar / 2) + 1); i++)
                    AddRow(ContentPanel);
            else
                for (int i = 1; i <= ((ncar / 2)); i++)
                    AddRow(ContentPanel);
            
            if (App.ViewModel.getNumbersOfVehicles() != 0)
            {
            //buttons creation, the vbutton name and/or content will be reded from DB
            for (int i = 0; i < ContentPanel.RowDefinitions.Count; i++)
                for (int j = 0; j < 2; j++)
                {
                    if (i != ContentPanel.RowDefinitions.Count - 1 | ncar % 2 != 1)
                    {
                        // TEST Per immagine nel bottone
                        var vbutton = new Button();
                        VehiclesTable Element = App.ViewModel.getElementWithID(IDlist[k]);
                        if (Element.ImageOfCar != null)
                        {
                            TextBlock nameOfCar = new TextBlock();
                            nameOfCar.Text = Element.VehicleName;
                            nameOfCar.HorizontalAlignment = HorizontalAlignment.Center;
                            StackPanel buttonStack = new StackPanel();
                            

                            // GET the image
                            BitmapImage imageOfVehicleToBeSetIntoButton = new BitmapImage();
                            using (IsolatedStorageFile myIsoStore = IsolatedStorageFile.GetUserStoreForApplication())
                            {
                                using (IsolatedStorageFileStream imageFileStream = myIsoStore.OpenFile(Element.ImageOfCar, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                                {
                                    imageOfVehicleToBeSetIntoButton.SetSource(imageFileStream);
                                }
                            }

                            Image buttonImage = new Image();
                            buttonImage.Source = imageOfVehicleToBeSetIntoButton;
                            buttonImage.Stretch = Stretch.UniformToFill;

                            buttonStack.Children.Add(buttonImage);
                            buttonStack.Children.Add(nameOfCar);

                            vbutton.Content = buttonStack;

                            // Same code of prima
                            vbutton.Name = Element.VId.ToString();
                            vbutton.Background = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
                            vbutton.BorderThickness = new Thickness(0);
                            Grid.SetColumn(vbutton, j);
                            Grid.SetRow(vbutton, i);
                            ContentPanel.Children.Add(vbutton);
                            vbutton.Click += new RoutedEventHandler(button_clicked);
                            k++;
                        }
                        else
                        {

                            //var vbutton = new Button();
                            //VehiclesTable Element = App.ViewModel.getElementWithID(IDlist[k]);
                            vbutton.Content = Element.VehicleName;
                            vbutton.Name = Element.VId.ToString();
                            vbutton.Background = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
                            vbutton.BorderThickness = new Thickness(0);
                            Grid.SetColumn(vbutton, j);
                            Grid.SetRow(vbutton, i);
                            ContentPanel.Children.Add(vbutton);
                            vbutton.Click += new RoutedEventHandler(button_clicked);
                            k++;
                        }
                    }
                    else
                    {
                        var vbutton = new Button();
                        VehiclesTable Element = App.ViewModel.getElementWithID(IDlist[k]);
                        if (Element.ImageOfCar != null)
                        {
                            TextBlock nameOfCar = new TextBlock();
                            nameOfCar.Text = Element.VehicleName;
                            nameOfCar.HorizontalAlignment = HorizontalAlignment.Center;
                            StackPanel buttonStack = new StackPanel();


                            // GET the image
                            BitmapImage imageOfVehicleToBeSetIntoButton = new BitmapImage();
                            using (IsolatedStorageFile myIsoStore = IsolatedStorageFile.GetUserStoreForApplication())
                            {
                                using (IsolatedStorageFileStream imageFileStream = myIsoStore.OpenFile(Element.ImageOfCar, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                                {
                                    imageOfVehicleToBeSetIntoButton.SetSource(imageFileStream);
                                }
                            }
                            Image buttonImage = new Image();
                            buttonImage.Source = imageOfVehicleToBeSetIntoButton;
                            buttonImage.Stretch = Stretch.UniformToFill;

                            buttonStack.Children.Add(buttonImage);
                            buttonStack.Children.Add(nameOfCar);

                            vbutton.Content = buttonStack;

                            // Same code of prima
                            vbutton.Name = Element.VId.ToString();
                            vbutton.Background = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
                            vbutton.BorderThickness = new Thickness(0);
                            Grid.SetColumn(vbutton, j);
                            Grid.SetRow(vbutton, i);
                            ContentPanel.Children.Add(vbutton);
                            vbutton.Click += new RoutedEventHandler(button_clicked);
                            j++;
                            k++;
                        }
                        else
                        {

                            //var vbutton = new Button();
                            //VehiclesTable Element = App.ViewModel.getElementWithID(IDlist[k]);
                            vbutton.Content = Element.VehicleName;
                            vbutton.Name = Element.VId.ToString();
                            vbutton.Background = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
                            vbutton.BorderThickness = new Thickness(0);
                            Grid.SetColumn(vbutton, j);
                            Grid.SetRow(vbutton, i);
                            ContentPanel.Children.Add(vbutton);
                            vbutton.Click += new RoutedEventHandler(button_clicked);
                            j++;
                            k++;
                        }

                    }
                }
        }
        }

        /// <summary>
        /// Handler for all the buttons in the grid, the button will be identified from his name
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_clicked(object sender, EventArgs e)
        {
            Button button = sender as Button;
            //add or update auto cliccked        
            if (!VehiclesData.Contains("AutoCliccked"))
                VehiclesData.Add("AutoCliccked", button.Name);
            else
                VehiclesData["AutoCliccked"] = button.Name;

            NavigationService.Navigate(new Uri("/Views/VehicleDetails.xaml", UriKind.Relative));

        }

        /// <summary>
        /// Add a row to a grid, with MaxHeight=MinHeight=200px
        /// </summary>
        /// <param name="g"></param>
        private void AddRow(Grid g)
        {
            RowDefinition rowDef = new RowDefinition();
            rowDef.MaxHeight = 200;
            rowDef.MinHeight = 200;
            g.RowDefinitions.Add(rowDef);
        }
        

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (e.NavigationMode == NavigationMode.Back)
            {
                EditContentPanel();
            }
        }
        
    }
}